import Vue from "vue";
import { Dialog } from "element-ui";

let instance;

/**
 * @method Modal 创建弹窗
 */

const Modal = function ({ component, methods, props, componentProps }) {
  //判断vue有没有在服务器商运行
  if (Vue.prototype.$isServer) return;

  //创建一个div元素在Body元素上
  const dom = document.createElement("div");

  document.body.appendChild(dom);

  //初始化一个vue
  instance = new Vue({

    //绑定根元素
    el: dom,

    data() {
      return {
        showModal: true,
      };
    },

    //引入组件
    components: {
      Dialog: Dialog,
      Plugin: component,
    },

    //渲染组件
    render(createElement) {
      const plugin = this.showModal
        ? () =>
            createElement("Plugin", {
              props: {
                ...componentProps,
              },
              on: {
                close: (e) => this.close(e),
                ...methods,
              },
            })
        : null;

      return createElement("Dialog", {
        props: {
          visible: this.showModal,
          ...props,
        },
        on: {
          close: (e) => this.close(e),
        },
        //createElement 可以插入插槽
        scopedSlots: {
          default: plugin,
        },
      });
    },
    methods: {
      close() {
        this.showModal = false;
        document.body.removeChild(this.$el);
        this.$destroy();
      },
    },
  });
  return instance;
};

export default Modal;
